﻿var ht = "";
var chay = 1;
var ajaxGetDanhSachPhieuKham = null;
var TABKEY = 9;
var ENTERKEY = 13;
var DanhMucThuoc = new Array(); //Lưu danh mục thuốc để chạy Autocomplete
var messageSearching = "Đang tìm kiếm, vui lòng đợi trong giây lát...";
var messageSaving = "Đang lưu dữ liệu, vui lòng đợi trong giây lát...";
var messageLoading = "Đang tải dữ liệu, vui lòng đợi trong giây lát...";
jQuery.fn.center = function () {
    var w = $(window);
    this.css("position", "fixed");
    this.css("top", w.height() / 2 - this.height() / 2 + "px");
    this.css("left", w.width() / 2 - this.width() / 2 + "px");
    return this;
}

$(document).ajaxStart(function () {
    showAjaxWaiting(true);
});

$(document).ajaxComplete(function () {
    showAjaxWaiting(false);
});

function Initilize()
{    
    var html = "<div id='overlay'></div>";
    html += "<div id=\"loader\" style=\"height:50px;z-index:999; width:210px; text-align:center\"> " +
            "     <img src=\"rs/ajax-loader.gif\" alt=\"Đang tìm kiếm, vui lòng đợi trong giây lát...\"/> <br /> " +
            "     <label id='messageHTML'>Đang tìm kiếm, vui lòng đợi trong giây lát...</label>   <br />" +            
            "</div>";
    $('body').append(html);
    $('#loader').center();
    $('#loader').hide();
    //Tao bang toa thuoc
    //TaoToaThuocPhongKham();   
    doiTrangThaiKiemTraThuoc();
    an_div();
}

function showAjaxWaiting(isShow)
{
    if (isShow)
    {
        $('#loader').show();
        $('#overlay').show();
    }
    else
    {
        $('#loader').hide();
        $('#overlay').hide();
    }
}

function tongtien() {
    var s = 0;
    var so_loai_thuoc = 0;
    for (var i = 1; i < document.all("hsodong").value; i++) {
        if (document.all("tenthuoc" + i.toString()).value != "") {
            s += (parseFloat(document.all("soluong" + i.toString()).value) * parseFloat(document.all("dongia" + i.toString()).value));
            so_loai_thuoc++;
        }
    }
    //document.all("tong").value = formatCurrency(s);
    //document.all("tong").value=s;
    if (s > 600000)
        alert('Tổng tiền toa thuốc đã vượt mức 600000 vnđ.');
    if (so_loai_thuoc > 6)
        alert('Đã có hơn 6 loại thuốc được kê trong toa.');
}

function formatCurrency(n) {
    var num = n;
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
        //num = num.substring(0,num.length-(4*i+3))+'.'+
        num.substring(num.length - (4 * i + 3));
    //return (((sign)?'':'-') + '$' + num + '.' + cents);
    return (((sign) ? '' : '-') + num);//+'đ');
}

function doiTrangThaiKiemTraThuoc() {
    /*if (document.getElementById("cktthuoc").checked==true)
        chay=1;			
    else chay=0;*/
}

function loadDanhSachBenhNhanCho() {
    $("#tblDSBNCho").empty();
    $("#tblDSBNCho").append(
        "<tr>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        STT" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Ngày Đăng Ký" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        MaBN" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Họ Tên" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Tuổi" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Loại Khám" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Trạng Thái" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Ưu Tiên" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-right: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Chọn" + "\n" +
        "    </th>" + "\n" +
        "</tr>" + "\n"
    );
    $.ajax({
        type: "GET",
        url: "Handler/XML_DanhSachBenhNhanCho.aspx?MaKhoa=" + $("#txtMaKhoa").val() +
             "&TuNgay=" + $("#txtTuNgay").val() +
             "&DenNgay=" + $("#txtDenNgay").val() +
             "&MaBN=" + $("#txtMaBN").val() +
             "&HoTen=" + $("#txtHoTen").val(),
        cache: false,
        dataType: "xml",
        success: function (xml) {
            var i = 0;
            $(xml).find("DanhSachBenhNhanCho").each(function () {
                i++;
                var UuTien = $(this).attr("UuTien");
                if (UuTien == "") {
                    UuTien = "&nbsp;";
                }
                $("#tblDSBNCho").append(
                    "<tr>" + "\n" +
                    "    <td style=\"height:20px; text-align:center;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px;\">" + "\n" +
                    "            " + $(this).attr("STT") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("Ngay") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("MaBN") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("HoTen") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("Tuoi") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("Loaikham") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("DaKeToa") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + UuTien + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px; text-align:center;" + "\n" +
                    "                border-right: solid 1px #AAAAAA;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px; background-color:#D3E6FD\">" + "\n" +
                    "       <a href=\"javascript:void(0)\" class=\"lnk2\" onclick=\"chonPhieuKham(" + "'" + $(this).attr("ID") + "', " + "'" + $(this).attr("MaBN") + "'" + ");\">" + "\n" +
                    "           Chọn" + "\n" +
                    //"           <img src=\"Images/btnDelete.png\" alt=\"\" width=\"20px\" height=\"20px\" border=\"0px\" />" + "\n" +
                    "       </a>" +
                    "    </td>" + "\n" +
                    "</tr>" + "\n"
                );
            });
        }
        //,
        //error: err
    });
}

function loadDanhSachPhieuKham(PageIndex, Action)
{
    $("#tableDanhSachPhieuKham").empty();
    $("#tableDanhSachPhieuKham").append(
        "<tr>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        STT" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Mã Phiếu Khám" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Ngày Khám" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Mã BN" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Họ Tên" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Bác Sĩ Khám" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Chẩn Đoán" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Loại Phiếu" + "\n" +
        "    </th>" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-right: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Chọn" + "\n" +
        "    <th style=\"height:30px;width:50px;font-size:12px;" + "\n" +
        "               border-top: solid 1px #AAAAAA;" + "\n" +
        "               border-right: solid 1px #AAAAAA;" + "\n" +
        "               border-bottom: solid 1px #AAAAAA;" + "\n" +
        "               border-left: solid 1px #AAAAAA;\">" + "\n" +
        "        Xem" + "\n" +
        "    </th>" + "\n" +
        "</tr>" + "\n"
    );

    var MaPhieu = $('#txtDSPK_MaPhieu').val();
    var BacSi = $('#txtDSPK_BacSi').val();
    //if (BacSi == 'admin') BacSi = '';
    var TuNgay = $('#txtDSPK_TuNgay').val();
    var DenNgay = $('#txtDSPK_DenNgay').val();
    var MaBN = $('#txtDSPK_MaBN').val();
    var HoTenBN = $('#txtDSPK_TenBN').val();
    var XuTri = $('#dropDownDSPK_XuTri').val();
    var MaKhoa = $('#hid_makhoa').val();
    $.ajax({
        url: 'Handler/XML_DanhSachPhieuKham.ashx',
        data: {
            MaPhieu: MaPhieu,
            BacSi: BacSi,
            TuNgay: TuNgay,
            DenNgay: DenNgay,
            MaBN: MaBN,
            TenBN: HoTenBN,
            XuTri: XuTri,
            MaKhoa: MaKhoa,
            PageIndex: PageIndex,
            Action: Action
        },
        contentType: "text/xml; charset=utf-8",        
        type: 'get',
        timeout: 10000,
        beforeSend: function ()
        {
            showAjaxWaiting(true);
        },
        success: function (xmlResponse) {
            showAjaxWaiting(false);
            var htmlTable = "";
            var LoaiKham = "";
            var XuTri = "";
            var scriptChon = "";
            $("DanhSachPhieuKham", xmlResponse).map(function () {
                if ($(this).attr("LoaiPhieu") == 'khamchinh')
                    LoaiKham = 'Khám chính';
                else
                    LoaiKham = 'Khám thêm';
                XuTri = $(this).attr("XuTri");
                
                htmlTable += "<tr>" + "\n" +
                    "    <td style=\"height:20px; text-align:center;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px;\">" + "\n" +
                    "            " + $(this).attr("STT") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("MaPK") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("Ngay") + "\n" +
                    "    </td>" + "\n" +
                     "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("MaBN") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px; white-space: nowrap;\">" + "\n" +
                    "            " + $(this).attr("HoTen") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("TenBS") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + $(this).attr("ChanDoan") + "\n" +
                    "    </td>" + "\n" +
                    "    <td style=\"height:20px;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px\">" + "\n" +
                    "            " + LoaiKham + "\n" +
                    "    </td>" + "\n" +                    
                    "   <td style=\"height:20px; text-align:center;" + "\n" +
                    "                border-right: solid 1px #AAAAAA;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px;background-color:#D3E6FD\">" + "\n" +
                    "       <a href=\"javascript:void(0)\" class=\"lnk2\" onclick=\"dienThongTinBNTuDSPK('" + $(this).attr('LoaiPhieu') + "', " + "\n" +
                    "                                                                                    '" + $(this).attr('KetThuc') + "', " + "\n" +
                    "                                                                                    '" + $(this).attr('MaDotKham') + "', " + "\n" +
                    "                                                                                    '" + $(this).attr('Ngay') + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("MaPK") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("MaPhieuKhamChinh") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("MaBN") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("DoiTuong") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("HoTen") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("NamSinh") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("SoBHYT") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("HanBH") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("GioiTinh") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("TrieuChung") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ChanDoanSoBo") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ICDChanDoan") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ChanDoan") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ICDChanDoanPhu1") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ChanDoanPhu1") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ICDChanDoanPhu2") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ChanDoanPhu2") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("LoiDanBS") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("ChiDinhDieuTri") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("TenBS") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("DaKeToa") + "', " + "\n" +
                    "                                                                                    '" + $(this).attr("XuTri") + "' " + "\n" +
                    "                                                                                    )\">" + "\n" +
                    "           Chọn" + "\n" +
                    "       </a>" +
                    "    <td style=\"height:20px; text-align:center;" + "\n" +
                    "                border-right: solid 1px #AAAAAA;" + "\n" +
                    "                border-bottom: solid 1px #AAAAAA;" + "\n" +
                    "                border-left: solid 1px #AAAAAA;" + "\n" +
                    "                padding-top:5px; padding-left:5px; padding-right:5px; background-color:#D3E6FD\">" + "\n" +
                    "       <a href=\"javascript:void(0)\" class=\"lnk2\" onclick=\"inToaThuoc('" + $(this).attr("MaPK") + "', '" + $(this).attr("HoTen") + "', '" + $(this).attr("NamSinh") + "', '" + $(this).attr("SoBHYT") + "', '" + $(this).attr("HanBH") + "')\">" + "\n" +
                    "           Xem" + "\n" +
                    "       </a>" +
                    "    </td>" + "\n" +
                    "</tr>" + "\n";
            });

            $("#tableDanhSachPhieuKham").append(htmlTable);
            var htmlPaging = "";
            var tongSoRecord = 0;
            $(xmlResponse).find('TongSoRecord').each(function () {
                tongSoRecord = $(this).attr('TongSo');
            });
            $('#lblKetQuaDSPK').html(tongSoRecord + ' kết quả được tìm thấy');
            var pages = Math.ceil(tongSoRecord / 10);            
            if (pages > 10)
            {
                for (var i = 1; i <= 10; i++) {
                    if (i == PageIndex) {
                        htmlPaging += "<span class=\"page active\">" + i + "</span>";
                    }
                    else {
                        htmlPaging += "<a href=\"javascript:void(0)\" class=\"page gradient\" onclick=\"loadDanhSachPhieuKham('" + i + "', 'GetPage')\">" + i + "</a>";
                    }
                }
                htmlPaging += "<a href=\"javascript:void(0)\" class=\"page gradient\" onclick=\"loadDanhSachPhieuKham('', 'GetPage')\">...</a>";
                htmlPaging += "<a href=\"javascript:void(0)\" class=\"page gradient\" onclick=\"loadDanhSachPhieuKham('" + pages + "', 'GetPage')\" title=\"Đến trang cuối cùng\">Cuối</a>";
            }
            else
            {
                for (var i = 1; i <= pages; i++) {
                    if (i == PageIndex) {
                        htmlPaging += "<span class=\"page active\">" + i + "</span>";
                    }
                    else {
                        htmlPaging += "<a href=\"javascript:void(0)\" class=\"page gradient\" onclick=\"loadDanhSachPhieuKham('" + i + "', 'GetPage')\">" + i + "</a>";
                    }
                }
            }
           
            //$('#htmlPagingDSPK').html("<a href=\"#\" class=\"page gradient\" title=\"Về trang đầu\">Đầu</a> " +
            //                    "<a href=\"#\" class=\"page gradient\">2</a> " +
            //                    "<a href=\"#\" class=\"page gradient\">3</a> " +
            //                    "<span class=\"page active\">4</span>" +
            //                    "<a href=\"#\" class=\"page gradient\">5</a> " +
            //                    "<a href=\"#\" class=\"page gradient\">6</a> " +
            //                    "<a href=\"#\" class=\"page gradient\" title=\"Đến trang cuối cùng\">Cuối</a>");
            $('#htmlPagingDSPK').html(htmlPaging);
        },
        error: function () {
            showAjaxWaiting(false);
        }
    });
}

function loadThongTinPhieuKham(MaPhieu)
{
    $.ajax({
        url: 'Handler/XML_DanhSachPhieuKham.ashx',
        data: {MaPhieu: MaPhieu, Action: 'ViewChiTietToaThuoc'},
        type: 'get',
        beforeSend: function(){ showAjaxWaiting(true); },
        success: function(xmlReturn){
            showAjaxWaiting(false);
            var message = xmlReturn.getElementsByTagName('Message');
            if (message != '' || message != null)
            {
                alert($(message).attr('Text'));
            }
            else
            {
                var currentDate = new Date();
                var GioiTinh = 0;
                $('PhieuKham', xmlReturn).map(function () {
                    $('#mapk').val($(this).attr('MaPK'));
                    $('#txtmaphieucu').val($(this).attr('MaPK'));
                    $('#txtmapk_chinh').val($(this).val('MaPhieuKhamChinh'));
                    $('#mabn').val($(this).attr('MaBN'));
                    $('#tenbn').val($(this).attr('HoTen'));
                    $('#tuoi').val(currentDate.getFullYear() - parseInt($(this).attr('NamSinh')));
                    $('#txtSoBHYT').val($(this).attr('SoBHYT'));
                    $('#txtHanBHYT').val($(this).attr('HanBH'));
                    $('#trieuchung').val($(this).attr('TrieuChung'));
                    $('#txtChanDoanSoBo').val($(this).attr('ChanDoanSoBo'));
                    $('#icd').val($(this).attr('ICDChanDoan'));
                    $('#chandoan').val($(this).attr('ChanDoan'));
                    $('#icdphu1').val($(this).attr('ICDChanDoanPhu1'));
                    $('#chandoanphu1').val($(this).attr('ICDChanDoanPhu1'));
                    $('#icdphu2').val($(this).attr('ICDChanDoanPhu2'));
                    $('#chandoanphu2').val($(this).attr('ICDChanDoanPhu2'));                    
                    if ($(this).attr('GioiTinh') == 'Nam') GioiTinh = 1; else GioiTinh = 0;
                    $('#rgioitinh').val(GioiTinh);
                    $('#chidinhdieutri').val($(this).attr('ChiDinhDieuTri'));
                    $('#loidanbs').val($(this).attr('LoiDanBS'));
                });
                $('#hKieuLuu').val('capnhat');
            }
        }
    });    
}

function dienThongTinBNTuDSPK(LoaiKham, KetThuc, MaDotKham, NgayKham, MaPhieu, MaPhieuKhamChinh, MaBN, DoiTuong, HoTen, NamSinh, SoBHYT, HanBH, GioiTinh, TrieuChung, ChanDoanSoBo, ICD, ChanDoan, ICDP1, ChanDoanP1, ICDP2, ChanDoanP2, LoiDanBS, ChiDinhDieuTri, BacSiKham, DaKeToa, XuTri) {
    if (KetThuc == 'True') {
        alert('Bệnh nhân này đã kết thúc khám. Không thể chỉnh sửa');
        return;
    }
    var HasEdit = true; //Kiểm tra xem có cho phép chỉnh sửa không, nếu có thì sẽ load thông tin đổ lên phiếu khám
    $.get('Handler/XML_DanhSachPhieuKham.ashx', {
        MaPhieu: MaPhieu,
        Action: 'ViewChiTietToaThuoc',
        MaKhoa: $('#hid_makhoa').val()
    }).done(function (xmlResponse) {
        var htmlThuoc = "";
        var i = 0;
        var message = xmlResponse.getElementsByTagName('Message');
        if (message != '' || message != null) {
            alert($(message).attr('Text'));
            HasEdit = false; //Khi có message cảnh báo trả về, tức là không cho phép chỉnh sửa
        }
        else {
            switch (XuTri) {
                case 'ketoa':
                    $('#dsxutri').val('ketoa');
                    $('#divPanelToaThuoc').css('display', 'block');
                    $('#tableToaThuoc tbody').empty();
                    $('ToaThuoc', xmlResponse).map(function (index) {
                        i = index + 1;
                        htmlThuoc += "<tr style=\"vertical-align:top;\">" +
                        "             <td style=\"width: 18px; vertical-align:middle; text-align:center\">" + i + "</td>" +
                        "             <td style=\"width: 240px\"><input type=\"text\" class=\"autocompleteTenThuoc\" style=\"width:240px\" id=\"txtTenThuoc_" + i + "\" value=\"" + $(this).attr('TenThuoc') + "\"/><input type='hidden' id=\"hdfIDThuoc_" + i + "\" value=\"" + $(this).attr('ID') + "\"/></td>" +
                        "             <td style=\"width: 40px\"><input type=\"text\"  style=\"width:47px\" id=\"txtSoLuong_" + i + "\" value=\"" + $(this).attr('SoLuong') + "\"/></td>" +
                        "             <td style=\"width: 48px\"><input type=\"text\"  style=\"width:48px\" id=\"txtDonVi_" + i + "\" value=\"" + $(this).attr('DonVi') + "\"/></td>" +
                        "             <td style=\"width: 80px\"><input type=\"text\"  style=\"width:80px\" id=\"txtCachDung_" + i + "\" value=\"" + $(this).attr('CachDung') + "\"/></td>" +
                        "             <td style=\"width: 56px\"><input type=\"text\"  style=\"width:56px\" id=\"txtLanDung_" + i + "\" value=\"" + $(this).attr('SoLanDung') + "\"/></td>" +
                        "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtLuongDung_" + i + "\" value=\"" + $(this).attr('LuongDung') + "\"/></td>" +
                        "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtDonViDung_" + i + "\" value=\"" + $(this).attr('DonViDung') + "\"/></td>" +
                        "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtGhiChu_" + i + "\" value=\"" + $(this).attr('GhiChu') + "\"/></td>" +
                        "             <td style=\"width: 72px\"><input type=\"text\"  class=\"DonGiaThuoc\" style=\"width:72px\" id=\"txtGia_" + i + "\" value=\"" + $(this).attr('DonGia') + "\"/></td>" +
                        "             <td><input type=\"button\" value=\"xóa\" id=\"btnClear_" + i + "\" onclick=\"ClearToaThuoc(this.id)\" /></td>" +
                        "             <td style=\"width: 27px\"></td> " +
                        "             <td></td>"
                        htmlThuoc += "</tr>";
                    });
                    $('#tableToaThuoc tbody').html(htmlThuoc);
                    TinhTienToaThuoc();
                    setAutoCompleteToInputThuoc();
                    break;
            }
        }
    });

    if (HasEdit) //Nếu cho phép chỉnh sửa, load các thông tin lên form
    {
        $('#hKieuLuu').val('capnhat');
        var currentDate = new Date();
        $('#mapk').val(MaPhieu);
        $('#txtmaphieucu').val(MaPhieu);
        $('#txtmapk_chinh').val(MaPhieuKhamChinh);
        $('#hiden_dotkham').val(MaDotKham);
        $('#tenbs').html(BacSiKham);
        $('#hidden_LoaiKham').val(LoaiKham);
        if (LoaiKham == 'khamchinh')
            LoaiKham = 'Khám chính';
        else
            LoaiKham = 'Khám thêm';
        $('#lblLoaiKham').html(LoaiKham);
        $('#mabn').val(MaBN);
        $('#hdf_DoiTuongBN').val(DoiTuong);
        $('#tenbn').val(HoTen);
        $('#txtSoBHYT').val(SoBHYT);
        $('#txtHanBHYT').val(HanBH);
        $('#ngay').val(NgayKham);
        var Tuoi = currentDate.getFullYear() - parseInt(NamSinh);
        $('#tuoi').val(Tuoi);
        $('#trieuchung').val(TrieuChung);
        $('#txtChanDoanSoBo').val(ChanDoanSoBo);
        $('#icd').val(ICD);
        $('#chandoan').val(ChanDoan);
        $('#icdphu1').val(ICDP1);
        $('#chandoanphu1').val(ChanDoanP1);
        $('#icdphu2').val(ICDP2);
        $('#chandoanphu2').val(ChanDoanP2);
        if (GioiTinh == 'Nam') GioiTinh = 1; else GioiTinh = 0;
        $('#rgioitinh').val(GioiTinh);
        $('#chidinhdieutri').val(ChiDinhDieuTri);
        $('#loidanbs').val(LoiDanBS);
        $('#divDanhSachPhieuKham').dialog('close');
    }    
}

function inToaThuoc(MaPhieu, HoTen, NgaySinh, SoBHYT, HanBH)
{
    window.open("In/intoathuoc_kc.aspx?maphieu=" + MaPhieu + "&HoTen=" + HoTen + "&NgaySinh=" + NgaySinh + "&SoBHYT=" + SoBHYT + "&HanBH=" + HanBH);
}

function loadBangSinhHieu()
{
    $('#divBody').show();
    if (ht == "") {
        document.body.style.overflow = 'hidden';
        ht = "x";
        x = $('#btnSinhHieu').offset().left;
        y = $('#btnSinhHieu').offset().top;

        $('#divSinhHieu').css({ left: x - 400, top: 3 });
        $('#iframeSinhHieu').css({ left: x - 400, top: 19 });
        $("#divSinhHieu").show();
        $("#iframeSinhHieu").show();
        //19.3.13
        window.frames['iframeSinhHieu'].document.getElementById('txtMaBN').value = document.getElementById('mabn').value;
        window.frames['iframeSinhHieu'].document.getElementById('cmLayTT').click();
        //end 19.3.13
        //txtMaBN
        //$("#drphong").hide();
        //$("#drdoituong").hide();
        //$("#drkhoa").removeAttr('disabled');
        //$("#drkhoa").hide();
        //chonbn();
    } else {
        document.body.style.overflow = 'auto';
        ht = "";
        $("#divSinhHieu").hide();
        $("#iframeSinhHieu").hide();
        $('#divBody').hide();
    }
}

function loadSuaTTBenhNhan()
{
    var _mabn = $("#mabn").val();
    if (_mabn == "") { return false; }
    $('#ifSuaThongTin').attr('src', "../TiepNhan_QN/SuaThongTinBN.aspx?mabn=" + _mabn + "&mand=" + $("#txtmanv").val());
    $('body').css('overflow', 'hidden');
    $('#divDialog').dialog("open");
}

function kiemTraTuongTacThuoc() {    
    var rows = document.getElementById('tableToaThuoc').getElementsByTagName('tr');
    var IDThuoc1 = "";
    var TenThuoc1 = "";
    var IDThuoc2 = "";
    var TenThuoc2 = "";
    $("#txtMessageInfo").empty();
    for (i = 1; i < rows.length - 1; i++) {
        if (document.all("hdfIDThuoc_" + i).value != "") {
            for (j = i + 1; j < rows.length - 1; j++) {
                IDThuoc1 = document.all("hdfIDThuoc_" + i).value;
                TenThuoc1 = document.all("txtTenThuoc_" + i).value;
                IDThuoc2 = document.all("hdfIDThuoc_" + j).value;
                TenThuoc2 = document.all("txtTenThuoc_" + j).value;
                if (IDThuoc1 != IDThuoc2 && IDThuoc1 != "" && IDThuoc2 != "") {
                    $.ajax({
                        type: "GET",
                        url: "Handler/XML_KiemTraPhanUngThuoc.aspx?IDThuoc=" + IDThuoc1 +
                             "&TenThuoc=" + TenThuoc1 +
                             "&IDThuoc2=" + IDThuoc2 +
                             "&TenThuoc2=" + TenThuoc2 +
                             "&ViewType=2",
                        cache: false,
                        dataType: "xml",
                        success: function (xml) {
                            $(xml).find("PUT").each(function () {
                                if ($(this).attr("Mess") != "") {
                                    var Mess = $(this).attr("Mess");

                                    Mess = Mess.replace(/~b/g, "<b>");
                                    Mess = Mess.replace(/b~/g, "</b>");
                                    Mess = Mess.replace(/~i/g, "<i>");
                                    Mess = Mess.replace(/i~/g, "</i>");
                                    Mess = Mess.replace(/~u/g, "<u>");
                                    Mess = Mess.replace(/u~/g, "</u>");
                                    Mess = Mess.replace(/~n/g, "<br/>");
                                    Mess = Mess.replace(/~hr/g, "<hr/>");
                                    $("#txtMessageInfo").append(Mess);
                                }
                            });
                        },
                        error: function (err) {
                            console.log(err);
                        }
                    });
                }
            }
        }
    }
    $("#dialog-KiemTraTuongTacThuoc").dialog("open");
}

function mocuasocon(url) {
    var x = window.open(url, "cuasocon", "status=yes,scrollbars=yes,resizable");
    x.focus();
}

function mocuasocon_Luu(url, nut) {
    //if((document.getElementById("txtloai_kham_CP").value!="khamthem") &&(url=="0")){
    document.getElementById("loaicd").value = url;
    document.getElementById(nut).disabled = true;
    document.getElementById("btnLuuKhongXoaDSCho").click();
    //alert(document.getElementById('txtmdk').value);
    //alert(document.all('mapk').value);
    //}else{alert("Khám thêm không có quyền sử dụng chức năng này!");}
}

function cuaSoInToa(maphieu) {
    var loai_kham = document.getElementById("txtloai_kham_CP").value;
    //2.4.13
    if (loai_kham == "khamthem") {
        //window.open("intoathuoc.aspx?maphieu="+maphieu);
        window.open("intoathuoc_kc.aspx?maphieu=" + maphieu);
        /*  if(ht1==""){
              //src.dis;alert(5);
              ht1="x";
              x=$('#btnSinhHieu').offset.left; 
              y=$('#btnSinhHieu').offset.top; 
              $('#ifrInTThuoc').css({left:170,top:35});
              $('#divInThuoc').css({left:170,top:5});
              //$('#DivId').attr('src', newimage); 
              $("#ifrInTThuoc").attr("src","intoathuoc.aspx?maphieu="+maphieu);		        
              $("#divInThuoc").show();
              $("#ifrInTThuoc").show();
              $("#divBody").show();
              document.body.style.overflow = 'hidden';
              //myPrint();
          }else{
              //src.en;
              ht1="";
              $("#divInThuoc").hide();
              $("#ifrInTThuoc").hide();
              document.body.style.overflow = 'sroll';		        
          }	*/
    }
    else {
        window.open("intoathuoc_kc.aspx?maphieu=" + maphieu);

        /*  if(ht2==""){
                 //src.dis;alert(6);
                 ht2="x";
                 x=$('#btnSinhHieu').offset.left; 
                 y=$('#btnSinhHieu').offset.top; 
                 //alert(x);alert(y);
                 //$('#ifrInTThuoc').css({left:x-400,top:y+23});
                 $('#ifrInTThuoc').css({left:170,top:35});
                 $('#divInThuoc').css({left:170,top:5});
                 $("#ifrInTThuoc").attr("src","intoathuoc_kc.aspx?maphieu="+maphieu);
                 
                 $("#divInThuoc").show();
                 $("#ifrInTThuoc").show();
                 $("#divBody").show();
                 document.body.style.overflow = 'hidden';
                 //myPrint();
             }else{
                 //src.en;
                 ht2="";
                 $("#ifrInTThuoc").hide();
                  $("#divInThuoc").hide();
                  $("#divBody").hide();
                  document.body.style.overflow = 'sroll';
                  
             }*/
    }
    //end 2.4.13
}

function cuaPhieuchuyenkhoa(maphieu, mabn, makhoa) {
    //window.open("in_phieuchuyenkhoa.aspx?maphieu="+maphieu + "&mabn="+mabn+"&makhoachuoi="+makhoa);
    if (ht3 == "") {

        ht3 = "x";
        x = $('#btnSinhHieu').offset.left;
        y = $('#btnSinhHieu').offset.top;
        //alert(x);alert(y);
        //$('#ifrInTThuoc').css({left:x-400,top:y+23});
        $('#ifrInTThuoc').css({ left: 170, top: 35 });
        $('#divInThuoc').css({ left: 170, top: 5 });
        $("#ifrInTThuoc").attr("src", "in_phieuchuyenkhoa.aspx?maphieu=" + maphieu + "&mabn=" + mabn + "&makhoachuoi=" + makhoa);

        $("#divInThuoc").show();
        $("#ifrInTThuoc").show();
        $("#divBody").show();
        document.body.style.overflow = 'hidden';
        //myPrint();
    } else {
        ht3 = "";
        $("#divInThuoc").hide();
        $("#ifrInTThuoc").hide();
        $("#divBody").hide();
        document.body.style.overflow = 'auto';

    }
}

function cuaSoTraCuu(txtchandoan, txticd) {
    y = window.open("tracuuicd10.aspx?tcd=" + txtchandoan + "&ticd=" + txticd, "tracuuICD", "scrollbars=yes,resizable=yes");
    y.focus();
}

function laytoacu() {
    w = window.open("laytoacu.aspx?mabn=" + document.all("mabn").value, "DSPK", "scrollbars=yes,resizable=yes");
    w.focus();
}

function kevattu() {
    var x = window.open("../qlkhoa/phieuvattuyte.aspx?mand=" + document.getElementById("txtmanv").value + "&mabn=" + document.all('mabn').value + "&madotkham=" + document.all('hiden_dotkham').value + "&mkhoa=" + document.getElementById("hid_makhoa").value, "cuasocon", "location=yes,status=yes,scrollbars=yes,resizable");
    x.focus();
}

function cuaSoDSPK() {
    w = window.open("danhsachphieukham_bm.aspx?mabs=" + document.all("hmabs").value, "DSPK", "scrollbars=yes,resizable=yes");
    w.focus();
}

function an_div() {
    document.getElementById("divChuyenVien").style.visibility = "hidden";
    document.getElementById("divNoiTru").style.visibility = "hidden";
    document.getElementById("divNgoaiBA").style.display = "none";
    //document.getElementById("divNgoaiBA_0").style.display = "none";
    document.getElementById("divChuyenVien").style.visibility = "hidden";
    //document.getElementById("divNgoai").style.display = "none";
    document.getElementById("div_chuyenkhoa").style.display = "none";
    //document.getElementById("div_khamthem").style.display="none";
}

function dsxutri_onchange() {
    an_div();
    $('#divKeToa').css('display', 'none');
    if (window.document.getElementById("dsxutri").value == "gioithieu") {
        if (document.getElementById("txtloai_kham_CP").value != "khamthem") {
            //document.getElementById("divNgoai").style.left = (CalculateLeft(document.getElementById("dsxutri")) + 1) + "px";
            //document.getElementById("divNgoai").style.top = (CalculateTop(document.getElementById("dsxutri")) + 45) + "px";
            //document.getElementById("divNgoai").style.display = "block";
            $('#divChuyenVien_S').dialog("open");
        } else { alert("Khám thêm không có quyền sử dụng chức năng này!"); document.getElementById("dsxutri").value = "0"; }
    }
    else if (window.document.getElementById("dsxutri").value == "nhapvien") {
        //if(document.getElementById("txtloai_kham_CP").value!="khamthem"){
        //document.getElementById("divNoiTru").style.visibility="visible";
        //document.getElementById("divNgoaiBA").style.left=(CalculateLeft(document.getElementById("dsxutri"))+1)+"px";			
        //document.getElementById("divNgoaiBA").style.top= (CalculateTop(document.getElementById("dsxutri"))+45)+"px";
        //document.getElementById("divNgoaiBA_0").style.left = (CalculateLeft(document.getElementById("dsxutri")) + 1) + "px";
        //document.getElementById("divNgoaiBA_0").style.top = (CalculateTop(document.getElementById("dsxutri")) + 45) + "px";
        //Cho hien thi div Thong Tin Nhap Vien
        //document.getElementById("divNgoaiBA_0").style.display = "block";        
        $('#divNhapVien_S').dialog("open");
        //document.getElementById("txtcd_pk_BA").value=document.getElementById("chandoan").value;
        //}else{alert("Khám thêm không có quyền sử dụng chức năng này!");document.getElementById("dsxutri").value="0";}
    }
    else if (window.document.getElementById("dsxutri").value == "ngoaitru") {
        if (document.getElementById("txtloai_kham_CP").value != "khamthem") {
            //document.getElementById("divNgoaiBA_0").style.left = (CalculateLeft(document.getElementById("dsxutri")) + 1) + "px";
            //document.getElementById("divNgoaiBA_0").style.top = (CalculateTop(document.getElementById("dsxutri")) + 45) + "px";
            //Cho hien thi div Thong Tin Nhap Vien
            $('#divNhapVien_S').dialog("open");
           // document.getElementById("divNgoaiBA_0").style.display = "block";
            //document.getElementById("txtcd_pk_BA").value=document.getElementById("chandoan").value;
        } else { alert("Khám thêm không có quyền sử dụng chức năng này!"); document.getElementById("dsxutri").value = "0"; }
    }
    else if (window.document.getElementById("dsxutri").value == "ketoa") {
        loadDanhMucThuoc();
        $('#divKeToa').css('display', 'block');
        $('#tableToaThuoc tbody').empty();       
        TaoToaThuocPhongKham();
    }
    else if (window.document.getElementById("dsxutri").value == "chuyenkhoa") {
        if (document.getElementById("txtloai_kham_CP").value != "khamthem") {
            var _kt = document.getElementById("txtktckhoa").value;
            //LENH NAY THINH THEM VAO NGAY 080912 DE CHO PHEP CHYUEN KHOA KHI DA KE TOA
            //document.getElementById("div_chuyenkhoa").style.display="block";
            //DOAN DUOI NAY LA MA CU
            if (_kt == "2") { alert("Bệnh nhân đã được kê toa, không thể chuyển khoa!"); document.getElementById("dsxutri").value = "ketoa"; }
            else { document.getElementById("div_chuyenkhoa").style.display = "block"; }
        } else { alert("Khám thêm không có quyền sử dụng chức năng này!"); document.getElementById("dsxutri").value = "0"; }
    }
    else if (window.document.getElementById("dsxutri").value == "khamphu") {
        //document.getElementById("div_khamthem").style.display="block";
    }
}

function MoPhacDoMenu() {

    document.getElementById("phacdomenu").style.visibility = "visible";
    pageOffset2("phacdomenu", document.all("bLuuPhacDo"));

}

function TaoPhacDoMenu() {

    document.writeln(" <div id='phacdomenu' class='iemenu' onMouseover='highlightie5()' onMouseout='lowlightie5()' style='color: black;font-size:11px; border-style:outset;padding-left:4; padding-right:4; padding-top:1; padding-bottom:1; border-width:1;position:absolute; left:11px; top:34px; z-index:1; background-color: #FFFFFF; layer-background-color: #999999; visibility: hidden;'>	");
    document.writeln("	<div class=menuitems onclick='HienCuaSoPD(\"cuasodspd\");NapDSPDItem();hidePDmenu();' >						");
    document.writeln("							");
    document.writeln("	Lưu vào đơn mẫu cũ... 						");
    document.writeln("	</div>						");
    document.writeln("	<div class=menuitems onclick='showCSPDMoi();hidePDmenu();' >						");
    document.writeln("	Lưu đơn mẫu mới... 						");
    document.writeln("	</div>						");
    document.writeln("	<div class=menuitems onclick='HienCuaSoPD(\"cuasoqlpd\");NapNoiDungQLPD();hidePDmenu();' >						");
    document.writeln("	Quản lý đơn mẫu... 						");
    document.writeln("	</div>						");
    document.writeln("							");
    document.writeln(" </div>					");
}

function showCSPDMoi() {
    var c1 = document.all("cuasopdmoi");
    var l1 = document.all("doLayer1");
    document.all("cuasopdmoi").style.posLeft = (document.body.offsetWidth / 2) - (c1.offsetWidth / 2);
    document.all("cuasopdmoi").style.posTop = (document.body.offsetHeight / 2) - (c1.offsetHeight / 2);

    l1.style.width = c1.offsetWidth;
    l1.style.height = c1.offsetHeight;
    l1.style.top = c1.style.top;
    l1.style.left = c1.style.left;
    l1.style.zIndex = c1.style.zIndex;
    l1.style.display = "block";
    document.all("cuasopdmoi").style.visibility = "visible";
    document.getElementById("txttenphacdo").style.backgroundColor = "Yellow";
    document.all("txttenphacdo").focus();
}

function hideCSPDMoi() {
    document.all("cuasopdmoi").style.visibility = "hidden";
    document.all("doLayer1").style.display = "none";
}

function TaoCuaSoDSPD() {
    document.writeln(" <div id='cuasodspd' class='iemenu'  style='color: black;font-size:11px; border-style:none;padding-left:0; padding-right:0; padding-top:0; padding-bottom:0; border-width:0;position:absolute; left:11px; top:34px; z-index:1; background-color: #FFFFFF; layer-background-color: #999999; visibility: hidden;'>	");
    document.writeln('						');
    document.writeln('	<TABLE  style="BORDER-RIGHT: gray 1px solid; BORDER-TOP: gray 1px solid; BORDER-LEFT: gray 1px solid; BORDER-BOTTOM: gray 1px solid" 	cellSpacing="0" cellPadding="0" width="300" border="0">	');
    document.writeln('			');
    document.writeln('		<TR>	');
    document.writeln('			<TD style="BORDER-RIGHT: gray 1px; BORDER-TOP: gray 1px; BACKGROUND-IMAGE: url(rs/barclassic24.jpg); BORDER-LEFT: gray 1px; BORDER-BOTTOM: gray 1px solid; HEIGHT: 20px" align="center">	');
    document.writeln('				<span>Danh sách đơn mẫu</span></TD> ');
    document.writeln('		</TR>	');
    document.writeln('		<TR>	');
    document.writeln('			<TD  style="HEIGHT: 100px; BACKGROUND-COLOR: white" >	');
    document.writeln('				<div align=center style="LINE-HEIGHT: 20px;" >Nhấn vào đơn mẫu để lưu </div> ');
    document.writeln('				<div id="dspditem"  onClick="itemdspdonclick();" onMouseover="highlightie5()" onMouseout="lowlightie5()" style="height:150px;overflow:auto;padding-left:0; padding-right:0; padding-top:20px; padding-bottom:0;border-bottom-color:gray;border-bottom-width:1px;border-bottom-style:solid;border-top-color:gray;border-top-width:1px;border-top-style:solid;">');
    document.writeln(' </div> ');
    document.writeln('				<div align="center" style="padding-left:0; padding-right:0; padding-top:5px; padding-bottom:5px;" > <input type=button class=tbox value="Đóng" onClick="AnCuaSoPD(\'cuasodspd\');" ></div>	');

    document.writeln('			</TD>	');
    document.writeln('		</TR>	');
    document.writeln('	</TABLE>	');
    document.writeln("	</div>				");
}

function TaoCuaSoQLPD() {
    document.writeln(" <div id='cuasoqlpd' class='iemenu'  style='color: black;font-size:11px; border-style:none;padding-left:0; padding-right:0; padding-top:0; padding-bottom:0; border-width:0;position:absolute; left:11px; top:34px; z-index:1; background-color: #FFFFFF; layer-background-color: #999999; visibility: hidden;'>	");
    document.writeln('						');
    document.writeln('	<TABLE  style="BORDER-RIGHT: gray 1px solid; BORDER-TOP: gray 1px solid; BORDER-LEFT: gray 1px solid; BORDER-BOTTOM: gray 1px solid" 	cellSpacing="0" cellPadding="0" width="300" border="0">	');
    document.writeln('			');
    document.writeln('		<TR>	');
    document.writeln('			<TD style="BORDER-RIGHT: gray 1px; BORDER-TOP: gray 1px; BACKGROUND-IMAGE: url(rs/barclassic24.jpg); BORDER-LEFT: gray 1px; BORDER-BOTTOM: gray 1px solid; HEIGHT: 20px" align="center">	');
    document.writeln('				<span>Quản lý đơn mẫu</span></TD> ');
    document.writeln('		</TR>	');
    document.writeln('		<TR>	');
    document.writeln('			<TD id="ndcsqlpd" style="HEIGHT: 100px; BACKGROUND-COLOR: white" >	');
    //	document.writeln('				<div align=center style="LINE-HEIGHT: 20px;" >Nhấn vào đơn mẫu để lưu </div> ');
    //	document.writeln('				<div id="dspditem"  onClick="itemdspdonclick();" onMouseover="highlightie5()" onMouseout="lowlightie5()" style="height:150px;overflow:auto;padding-left:0; padding-right:0; padding-top:20px; padding-bottom:0;border-bottom-color:gray;border-bottom-width:1px;border-bottom-style:solid;border-top-color:gray;border-top-width:1px;border-top-style:solid;">');
    //	document.writeln(' </div> ');
    //	document.writeln('				<div align="center" style="padding-left:0; padding-right:0; padding-top:5px; padding-bottom:5px;" > <input type=button class=tbox value="Đóng" onClick="AnCuaSoDSPD();" ></div>	');

    document.writeln('			</TD>	');
    document.writeln('		</TR>	');
    document.writeln('	</TABLE>	');
    document.writeln("	</div>				");
}

function TaoCuaSoTenPDMoi() {
    document.writeln(" <div id='cuasopdmoi' class='iemenu'  style='color: black;font-size:11px; border-style:none;padding-left:0; padding-right:0; padding-top:0; padding-bottom:0; border-width:0;position:absolute; left:11px; top:34px; z-index:1; background-color: #FFFFFF; layer-background-color: #999999; visibility: hidden;'>	");
    document.writeln('						');
    document.writeln('	<TABLE id="Table2" style="BORDER-RIGHT: gray 1px solid; BORDER-TOP: gray 1px solid; BORDER-LEFT: gray 1px solid; BORDER-BOTTOM: gray 1px solid" 	cellSpacing="0" cellPadding="0" width="300" border="0">	');
    document.writeln('			');
    document.writeln('		<TR>	');
    document.writeln('			<TD style="BORDER-RIGHT: gray 1px; BORDER-TOP: gray 1px; BACKGROUND-IMAGE: url(rs/barclassic24.jpg); BORDER-LEFT: gray 1px; BORDER-BOTTOM: gray 1px solid; HEIGHT: 20px" align="center">	');
    document.writeln('				<span id="Label3" >Lưu đơn mẫu mới</span></TD> ');
    document.writeln('		</TR>	');
    document.writeln('		<TR>	');
    document.writeln('			<TD style="HEIGHT: 100px; BACKGROUND-COLOR: white" align="center">	');
    document.writeln('				<p style="margin-left:10px;margin-right:10px">	');
    document.writeln('				<div style="padding-left:0; padding-right:0; padding-top:20px; padding-bottom:0;">Đặt tên đơn mẫu:	   ');
    document.writeln('				<input id=txttenphacdo type=textbox class=tbox onkeypress="if (event.keyCode==13){ rqLuuMoiPhacDo(document.all(\'txttenphacdo\').value);hideCSPDMoi();}" ></input> </div>  ');
    document.writeln('				<div style="padding-left:0; padding-right:0; padding-top:30px; padding-bottom:0;" > <input type=button class=tbox value="Lưu" OnClick="rqLuuMoiPhacDo(document.all(\'txttenphacdo\').value);hideCSPDMoi();" >&nbsp;&nbsp;&nbsp; <input type=button class=tbox value="Đóng" onClick="hideCSPDMoi();" ></div>	');
    document.writeln('				</p>	');
    document.writeln('			</TD>	');
    document.writeln('		</TR>	');
    document.writeln('	</TABLE>	');
    document.writeln("	</div>				");
}

function CalculateTop(oNode) {
    var iTop = 0;

    while (oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    return iTop;
}

function CalculateLeft(oNode) {
    var iLeft = 0;

    while (oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }

    return iLeft;
}

function anDivBS() {
    try {
        document.getElementById("divNgoai").style.display = "none";
        //document.getElementById("divContent").style.visibility="hidden";			
    } catch (err) { }
}

function anDivBA() {
    try {
        document.getElementById("divNgoaiBA_0").style.display = "none";
        //document.getElementById("divContentBA").style.visibility="hidden";			
    } catch (err) { }
}

function anDivCV() {

    try {
        document.getElementById("divNgoai").style.display = "none";
        //document.getElementById("divContentBA").style.visibility="hidden";			
    } catch (err) { }
}

function anDiv_TTBS() {
    try {
        document.getElementById("divNgoai_TTBS").style.display = "none";
        document.getElementById("divContent_TTBS").style.visibility = "hidden";
    } catch (err) { }
}

function seltext() {
    if (event.keyCode == 32 || event.keyCode == 13) {
        var tr = document.selection.createRange(); var txt = tr.duplicate();
        txt.moveStart("word", -1); creplace(txt);
    }
}

function creplace(tr) {
    for (var i = 0; dmmagotat[i]; i++) {
        if (tr.text == dmmagotat[i]) { tr.text = dmndgotat[i]; }
        if (tr.text == (dmmagotat[i] + " ")) { tr.text = dmndgotat[i]; }
        if (("." + tr.text) == dmmagotat[i]) { tr.moveStart("character", -1); tr.text = " " + dmndgotat[i]; }
        if (("." + tr.text) == (dmmagotat[i] + " ")) { tr.moveStart("character", -1); tr.text = " " + dmndgotat[i]; }
    }
}

function ktraform(nut, loai) {
    //alert(9);
    if (document.getElementById("icd").value == "") {
        alert("Chẩn đoán chưa đúng với mã ICD, Vui lòng nhập lại!");
    }
    else {
        document.getElementById("txtluu").value = loai;
        document.getElementById(nut).disabled = true;
        document.Form1.submit();
    }
}

function TaoToaThuocPhongKham()
{
    for(var i = 1 ; i <=5 ; i++)
    {
        insertNewRowToaThuoc(i);
    }
    setAutoCompleteToInputThuoc();
    loadCachDungThuoc();
}

function insertNewRowToaThuoc(i)
{
    var htmlThuoc = "<tr style=\"vertical-align:top;\">" +
             "             <td style=\"width: 18px; vertical-align:middle; text-align:center\">" + i + "</td>" +
             "             <td style=\"width: 240px\"><input type=\"text\" class=\"autocompleteTenThuoc\" style=\"width:240px\" id=\"txtTenThuoc_" + i + "\" /></td>" +
             "             <td style=\"width: 40px\"><input type=\"text\"  style=\"width:47px\" id=\"txtSoLuong_" + i + "\" onkeyup=\"TinhTienThuocTheoSoLuong(this.id, this.value)\"/></td>" +
             "             <td style=\"width: 48px\"><input type=\"text\"  class=\"autocompleteDonViThuoc\" style=\"width:48px\" id=\"txtDonVi_" + i + "\" /></td>" +
             "             <td style=\"width: 80px\"><input type=\"text\"  class=\"autocompleteCachDungThuoc\" style=\"width:80px\" id=\"txtCachDung_" + i + "\" /></td>" +
             "             <td style=\"width: 56px\"><input type=\"text\"  style=\"width:56px\" id=\"txtLanDung_" + i + "\" /></td>" +
             "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtLuongDung_" + i + "\" /></td>" +
             "             <td style=\"width: 72px\"><input type=\"text\"  class=\"autocompleteDonViThuoc\" style=\"width:72px\" id=\"txtDonViDung_" + i + "\" /></td>" +
             "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtGhiChu_" + i + "\" /></td>" +
             "             <td style=\"width: 72px\"><input type=\"text\"  class=\"DonGiaThuoc\" style=\"width:72px\" id=\"txtGia_" + i + "\" /><input type='hidden' id=\"hdfGia_" + i + "\" /></td>" +
             "             <td><input type=\"button\" value=\"xóa\" id=\"btnClear_" + i + "\" onclick=\"ClearToaThuoc(this.id)\" /></td>" +
             "             <td style=\"width: 27px\"></td> " +
             "             <td> " +
             "                  <input type='hidden' id=\"hdfIDThuoc_" + i + "\" /> " +
             "                  <input type='hidden' id=\"hdfDBName_" + i + "\" /> " +
             "                  <input type='hidden' class='tt-hoat-chat-chinh' id=\"hdfHCChinh_" + i + "\" /> " +
             "                  <input type='hidden' class='tt-ho-tri-lieu-' id=\"hdfHTLieu_" + i + "\" /> " +
             "             </td>";
   htmlThuoc += "</tr>";
   $('#hsodong').val(i);
   $('#tableToaThuoc tbody').append(htmlThuoc);
}

function loadDanhMucThuoc() {
    var NguonThuoc = '';
    if ($('#cnguonthuoc').is(':checked'))
        NguonThuoc = "BHYT";
    else
        NguonThuoc = "DV";
    $.ajax({
        url: 'Handler/XML_LoadDanhMucThuoc.ashx',
        type: 'get',
        data: { NguonThuoc: NguonThuoc },
        dataType: "xml",                
        contentType: "text/xml; charset=utf-8",
        beforeSend: function () { $('#messageHTML').html(messageLoading);},
        success: function (xmlResponse) {            
            $('Thuoc', xmlResponse).map(function () {
                var arrayItem = {
                    label: $(this).attr("TenThuoc") + " " + formatCurrency($(this).attr("DonGia").split(',')[0]) + "đ " + $(this).attr("SoLuongCon") + "/" + $(this).attr("DonVi"),
                    value: $(this).attr("TenThuoc"),
                    idthuoc: $(this).attr("ID"),
                    donvi: $(this).attr("DonVi"),
                    dongia: $(this).attr("DonGia"),
                    ghichu: $(this).attr("GhiChu"),
                    cachdung: $(this).attr('CachDung'),
                    dbname: $(this).attr('DBName'),
                    soluongcon: $(this).attr('SoLuongCon'),
                    hoatchatchinh: $(this).attr('HoatChatChinh')
                };
                DanhMucThuoc.push(arrayItem);
            });
        }
    });
}

function setAutoCompleteToInputThuoc()
{
    var NguonThuoc = '';
    if ($('#cnguonthuoc').is(':checked'))
        NguonThuoc = "BHYT";
    else
        NguonThuoc = "DV";
    $('.autocompleteTenThuoc').autocomplete({
        //source: function (request, response) {
        //    $.ajax({
        //        url: 'Handler/XML_TimTenThuoc.ashx',
        //        type: 'get',
        //        dataType: "xml",                
        //        contentType: "text/xml; charset=utf-8",
        //        data: { prefix: request.term, NguonThuoc: NguonThuoc },
        //        success: function (xmlResponse) {
        //            response($("Thuoc", xmlResponse).map(function () {
        //                return {
        //                    label: $(this).attr("TenThuoc") + " " + formatCurrency($(this).attr("DonGia").split(',')[0]) + "đ " + $(this).attr("SoLuongCon") + "/" + $(this).attr("DonVi"),
        //                    value: $(this).attr("TenThuoc"),
        //                    idthuoc: $(this).attr("ID"),
        //                    donvi: $(this).attr("DonVi"),
        //                    dongia: $(this).attr("DonGia"),
        //                    ghichu: $(this).attr("GhiChu"),
        //                    cachdung: $(this).attr('CachDung'),
        //                    dbname: $(this).attr('DBName'),
        //                    soluongcon: $(this).attr('SoLuongCon'),
        //                    hoatchatchinh: $(this).attr('HoatChatChinh')
        //                }
        //            }));
        //        }
        //    })
        //},
        source: DanhMucThuoc,
        focus: function (event, ui) {
            //default is ui.item.value
            $(this).val(ui.item.value);
            return false;
        },
        height: 50,
        max: 10,
        highlight: false,
        scroll: true,
        minLength: 0,
        cacheLength: 10,
        scrollHeight: 150,
        select: function (event, ui) {           
            var fullID = $(this).attr('id');
            var lastID = fullID.split('_')[1];
            var message = "";
            var isValid = true;
            //Kiểm tra khi nhấn phím Enter hoặc Tab.
            if (event.keyCode == TABKEY || event.keyCode == ENTERKEY) {
                //Kiểm tra trùng tên thuốc                
                var trungTen = KiemTraTrungTenThuocTrongToa(ui.item.value, lastID);
                if (!trungTen) {
                    message = "Đã có thuốc " + ui.item.value + " trong toa, hãy kê thêm số lượng nếu thấy cần thiết.";
                    $('#txtTenThuoc_' + lastID).val('');
                    isValid = false;
                    //Nếu nhấn Tab thì disable process, không cho nhảy sang ô khác
                    if (event.TABKEY == TABKEY) {
                        event.preventDefault();
                    }
                }
                else if ($('#chkTPThuoc').is(':checked') && ui.item.hoatchatchinh != '') //Nếu check Kiểm tra thành phần thuốc thì chạy kiểm tra
                {
                    //Kiểm tra trùng hoạt chất
                    //Nếu trùng thì alert cảnh báo và highlight màu đỏ, vẫn cho bác sĩ kê thuốc đó
                    var tenThuocTrungHoatChat = KiemTraTrungHoatChatTrongToa(ui.item.hoatchatchinh, lastID);
                    if (tenThuocTrungHoatChat != '') {
                        message = "Đã có hoạt chất " + ui.item.hoatchatchinh + " trong thuốc " + tenThuocTrungHoatChat;
                        $('#txtTenThuoc_' + lastID).css('color', 'red');
                        alert(message);
                        //Nếu nhấn Tab thì disable process, không cho nhảy sang ô khác
                        if (event.TABKEY == TABKEY) {
                            event.preventDefault();
                        }
                    }
                }

                if (!isValid) {
                    alert(message);
                }
                else {
                    $('#txtSoLuong_' + lastID).val('3');
                    $('#hdfIDThuoc_' + lastID).val(ui.item.idthuoc);
                    $('#hdfDBName_' + lastID).val(ui.item.dbname);
                    $('#txtGia_' + lastID).val(ui.item.dongia);
                    $('#hdfGia_' + lastID).val(ui.item.dongia);
                    $('txtGhiChu_' + lastID).val(ui.item.ghichu);
                    $('#txtDonVi_' + lastID).val(ui.item.donvi);
                    $('#txtCachDung_' + lastID).val(ui.item.cachdung);
                    $('#hdfHCChinh_' + lastID).val(ui.item.hoatchatchinh);
                    TinhTienToaThuoc();
                }
            }
            return false;
        }
    });

    $('.autocompleteCachDungThuoc').autocomplete({
        source: DMCDThuoc,
        height: 30,
        max: 10,
        highlight: false,
        scroll: true,
        minLength: 0,
        cacheLength: 10,
        scrollHeight: 30,
    });

    $('.autocompleteDonViThuoc').autocomplete({
        source: DVThuoc,
        height: 20,
        max: 10,
        highlight: false,
        scroll: true,
        minLength: 0,
        cacheLength: 10,
        scrollHeight: 30,
    });
}

function loadCachDungThuoc() {
    $.get('Handler/XML_CachDungThuoc.ashx').done(function (xmlReturn) {
        $('CachDungThuoc', xmlReturn).map(function () {
            DMCDThuoc.push($(this).attr('CachDung'));
        })

        $('DonViThuoc', xmlReturn).map(function () {
            DVThuoc.push($(this).attr('DonVi'));
        })
    })
}

function TinhTienThuocTheoSoLuong(id, soluong)
{
    if (soluong == '') soluong = 0;
    var lastID = id.split('_')[1];
    var DonGia = $('#hdfGia_' + lastID).val();
    var ThanhTien = parseFloat(DonGia) * parseInt(soluong);    
    $('#txtGia_' + lastID).val(ThanhTien);
    TinhTienToaThuoc();
}

function TinhTienToaThuoc() {
    var TongTien = 0;
    var DonGia = 0;
    var i = 0;
    $('.DonGiaThuoc').each(function (index) {
        i = index + 1;
        DonGia = $(this).val();
        if (DonGia != '') TongTien += parseFloat(DonGia);
    });

    $('#TongTienToaThuoc').val(formatCurrency(TongTien));
    if (TongTien > 600000)
        alert('Tổng tiền toa thuốc đã vượt mức 600.000 vnđ.');
    if (i > 6)
        alert('Đã có hơn 6 loại thuốc được kê trong toa.');
}

function KiemTraTrungTenThuocTrongToa(tenthuoc, lastID)
{
    var current = null;
    var id = 'txtTenThuoc_' + lastID;
    var returnValue = true;
    $('.autocompleteTenThuoc').each(function () {       
        current = $(this);        
        if (current.attr('id') != id && current.val() != '')
        {            
            if (current.val() == tenthuoc) {
                returnValue = false;
            }           
        }       
    });
    return returnValue;
}

function KiemTraTrungHoatChatTrongToa(hoatchat, lastID)
{
    //Lấy chữ đầu tiên trong hoạt chất chính để kiểm tra
    var firstWord_DangKe = hoatchat.split(' ')[0];    
    var current = null;
    var lastCurrentID = '';
    var id = 'hdfHCChinh_' + lastID;
    var returnValue = '';
    $('.tt-hoat-chat-chinh').each(function () {
        current = $(this);        
        if (current.attr('id') != id && current.val() != '') {
            if (current.val().indexOf(firstWord_DangKe) != -1) {
                //Trả về tên thuốc trùng hoạt chất
                lastCurrentID = current.attr('id').split('_')[1];
                returnValue = $('#txtTenThuoc_' + lastCurrentID).val();
                return false;
            }
        }
    });
    return returnValue;
}

function ClearToaThuoc(btnID)
{
    var lastID = btnID.split('_')[1];
    $('#txtTenThuoc_' + lastID).val('');
    $('#txtSoLuong_' + lastID).val('');
    $('#txtDonVi_' + lastID).val('');
    $('#txtCachDung_' + lastID).val('');
    $('#txtLanDung_' + lastID).val('');
    $('#txtLuongDung_' + lastID).val('');
    $('#txtDonViDung_' + lastID).val('');
    $('#txtGhiChu_' + lastID).val('');
    $('#txtGia_' + lastID).val('');
    $('#hdfIDThuoc_' + lastID).val('');
    $('#hdfDBName_' + lastID).val('');
    $('#hdfHCChinh_' + lastID).val('');
    $('#hdfHTLieu_' + lastID).val('');
    TinhTienToaThuoc();
}

function LoadDonThuocMau(id)
{    
    var mabs = $('#hmabs').val();
    var DoiTuong = $('#hdf_DoiTuongBN').val();
    var MaDT = '0';
    var songay = 1;
    switch(DoiTuong)
    {
        case 'BHYT':
            MaDT = '1';
            break;
        case 'DV':
            MaDT = '2';
            break;
    }
    var doituong = 1;
    $.get('Handler/XML_DonThuocMau.ashx',{
            lenh: 'select',
            dulieu: id,
            songay: songay,
            doituongbn: MaDT
    }).done(function (xmlResponse) {
        var htmlThuoc = "";
        var i = 0;
        $('#tableToaThuoc tbody').empty();
        $('Thuoc', xmlResponse).map(function (index) {
            i = index + 1;
            htmlThuoc += "<tr style=\"vertical-align:top;\">" +
            "             <td style=\"width: 18px; vertical-align:middle; text-align:center\">" + i + "</td>" +
            "             <td style=\"width: 240px\"><input type=\"text\" class=\"autocompleteTenThuoc\" style=\"width:240px\" id=\"txtTenThuoc_" + i + "\" value=\"" + $(this).attr('TenThuoc') + "\"/><input type='hidden' id=\"hdfIDThuoc_" + i + "\" value=\"" + $(this).attr('ID') + "\"/><input type='hidden' id=\"hdfDBName_" + i + "\" value=\"" + $(this).attr('DBName') + "\"/></td>" +
            "             <td style=\"width: 40px\"><input type=\"text\"  style=\"width:47px\" id=\"txtSoLuong_"+ i +"\" value=\""+ $(this).attr('SoLuong') +"\"/></td>" +
            "             <td style=\"width: 48px\"><input type=\"text\"  style=\"width:48px\" id=\"txtDonVi_"+ i +"\" value=\""+ $(this).attr('DonVi') +"\"/></td>" +
            "             <td style=\"width: 80px\"><input type=\"text\"  style=\"width:80px\" id=\"txtCachDung_"+ i +"\" value=\""+ $(this).attr('CachDung') +"\"/></td>" +
            "             <td style=\"width: 56px\"><input type=\"text\"  style=\"width:56px\" id=\"txtLanDung_"+ i +"\" value=\""+ $(this).attr('SoLanDung') +"\"/></td>" +
            "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtLuongDung_"+ i +"\" value=\""+ $(this).attr('LuongDung') +"\"/></td>" +
            "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtDonViDung_"+ i +"\" value=\""+ $(this).attr('DonViDung') +"\"/></td>" +
            "             <td style=\"width: 72px\"><input type=\"text\"  style=\"width:72px\" id=\"txtGhiChu_"+ i +"\" value=\""+ $(this).attr('GhiChu') +"\"/></td>" +
            "             <td style=\"width: 72px\"><input type=\"text\"  class=\"DonGiaThuoc\" style=\"width:72px\" id=\"txtGia_" + i + "\" value=\"" + $(this).attr('DonGia') + "\"/></td>" +
            "             <td><input type=\"button\" value=\"xóa\" id=\"btnClear_" + i + "\" onclick=\"ClearToaThuoc(this.id)\" /></td>" +
            "             <td style=\"width: 27px\"></td> "  +
            "             <td></td>"              
            htmlThuoc += "</tr>";                           
        });
        $('#tableToaThuoc tbody').html(htmlThuoc);
        TinhTienToaThuoc();
        setAutoCompleteToInputThuoc();
    });
}

function LuuToaThuoc()
{    
    var MaBN = $('#mabn').val();
    var MaKhoa = $('#hid_makhoa').val();
    var MaThuDV = $('#idthu').val();
    var MaBA = $('#txtMaBA').val();
    var MaDotKham = $('#hiden_dotkham').val();
    var MaPK = $('#mapk').val();
    var MaPhieuKhamChinh = $('#txtmapk_chinh').val();
    var MaPhieuCu = $('#txtmaphieucu').val();
    var TrieuChung = $('#trieuchung').val();
    var ChanDoanSoBo = $('#txtChanDoanSoBo').val();
    var ChanDoan = $('#chandoan').val();
    var ICDChanDoan = $('#icd').val();
    var ICDChanDoanPhu1 = $('#icdphu1').val();
    var ChanDoanPhu1 = $('#chandoanphu1').val();
    var ICDChanDoanPhu2 = $('#icdphu2').val();
    var ChanDoanPhu2 = $('#chandoanphu2').val();
    var XuTri = $('#dsxutri').val();
    var ChiDinhDieuTri = $('#chidinhdieutri').val();
    var LoiDanBS = $('#loidanbs').val();
    var HenTaiKham = $('#taikham').val();
    var NgayTaiKham = $('#txtNgay').val() + "/" + $('#txtGio').val() + "/" + $('#txtPhut').val();
    var MaBS = $('#hmabs').val();
    var BacSiKham = $('#tenbs').html();
    var LoaiKham = $('#hidden_LoaiKham').val();
    var IsThuocBH = $('#cnguonthuoc').val();
    var DoiTuongBN = $('#hdf_DoiTuongBN').val();
    var SoDongToaThuoc = $('#tableToaThuoc tr').length - 1;    
    var IDThuoc = "", tempIDThuoc = "";
    var TenThuoc = "", tempTenThuoc = "";
    var SoLuong = "", tempSoLuong = "";
    var CachDung = "", tempCachDung = "";
    var LuongDung = "", tempLuongDung = "";
    var LanDung = "", tempLanDung = "";
    var DonVi = "", tempDonVi = "";
    var DonViDung = "", tempDonViDung = "";
    var GhiChu = "", tempGhiChu = "";
    var Gia = "", tempGia = "";
    var DBName = "", tempDBName="";
    var message = "";
    var checkValid = true;
    //Nếu là kê toa thì kiểm tra các field nhập
    if (XuTri == 'ketoa')
    {
        for (var i = 1; i <= SoDongToaThuoc; i++) {
            IDThuoc = $('#hdfIDThuoc_' + i).val();
            TenThuoc = $('#txtTenThuoc_' + i).val();
            SoLuong = $('#txtSoLuong_' + i).val();
            CachDung = $('#txtCachDung_' + i).val();
            LuongDung = $('#txtLuongDung_' + i).val();
            LanDung = $('#txtLanDung_' + i).val();
            DonVi = $('#txtDonVi_' + i).val();
            DonViDung = $('#txtDonViDung_' + i).val();
            GhiChu = $('#txtGhiChu_' + i).val();
            Gia = $('#txtGia_' + i).val();
            DBName = $('#hdfDBName_' + i).val();
            if (IDThuoc != '') {
                tempIDThuoc += IDThuoc + "~";
                tempTenThuoc += TenThuoc + "~";
                tempDBName += DBName + "~";
                if (SoLuong == "" || SoLuong == "0") {
                    checkValid = false;
                    message = "Vui lòng nhập số lượng cho thuốc " + TenThuoc;
                    break;
                }
                else
                    tempSoLuong += SoLuong + "~";
                if (CachDung == "") {
                    checkValid = false;
                    message = "Vui lòng nhập cách dùng cho thuốc " + TenThuoc;
                    break;
                }
                else
                    tempCachDung += CachDung + "~";
                if (LuongDung == "") {
                    checkValid = false;
                    message = "Vui lòng nhập lượng dùng cho thuốc " + TenThuoc;
                    break;
                }
                else
                    tempLuongDung += LuongDung + "~";
                if (LanDung == "")
                {
                    checkValid = false;
                    message = "Vui lòng nhập lần dùng cho thuốc " + TenThuoc;
                    break;
                }
                else
                    tempLanDung += LanDung + "~";
                tempDonVi += DonVi + "~";
                if (DonViDung == "") {
                    checkValid = false;
                    message = "Vui lòng nhập đơn vị dùng cho thuốc " + TenThuoc;
                    break;
                }
                else
                    tempDonViDung += DonViDung + "~";
                if (GhiChu == "") GhiChu = "spaceYKN";
                tempGhiChu += GhiChu + "~";
                if (Gia == "")
                    Gia = "0";
                tempGia += Gia + "~";

            }
            else {
                alert(message);
                return;
            }
        }
        if(!checkValid)
            alert(message);
    }
    if (checkValid)
    {
        var KieuLuu = $('#hKieuLuu').val();
        $.ajax({
            url: 'Handler/Ajax_LuuPhieuKham.ashx',
            type: 'get',
            data: {
                MaPK: MaPK,
                MaKhoa: MaKhoa,
                MaBN: MaBN,
                MaDotKham: MaDotKham,
                MaBA: MaBA,
                MaThuDV: MaThuDV,
                LoaiKham: LoaiKham,
                MaPhieuKhamChinh: MaPhieuKhamChinh,
                MaPhieuCu: MaPhieuCu,
                TrieuChung: TrieuChung,
                ChanDoanSoBo: ChanDoanSoBo,
                ChanDoan: ChanDoan,
                ICDChanDoan: ICDChanDoan,
                ICDChanDoanPhu1: ICDChanDoanPhu1,
                ChanDoanPhu1: ChanDoanPhu1,
                ICDChanDoanPhu2: ICDChanDoanPhu2,
                ChanDoanPhu2: ChanDoanPhu2,
                XuTri: XuTri,
                ChiDinhDieuTri: ChiDinhDieuTri,
                LoiDanBS: LoiDanBS,
                HenTaiKham: HenTaiKham,
                NgayTaiKham: NgayTaiKham,
                MaBS: MaBS,
                TenBS: BacSiKham,
                IsThuocBH: IsThuocBH,
                DoiTuong: DoiTuongBN,
                KieuLuu: KieuLuu,
                IDThuoc_Arr: tempIDThuoc,
                TenThuoc_Arr: tempTenThuoc,
                SoLuong_Arr: tempSoLuong,
                DonVi_Arr: tempDonVi,
                DonViDung_Arr: tempDonViDung,
                CachDung_Arr: tempCachDung,
                LanDung_Arr: tempLanDung,
                LuongDung_Arr: tempLuongDung,
                GhiChu_Arr: tempGhiChu,
                Gia_Arr: tempGia,
                DBName_Arr: tempDBName
            },
            contentType: "text/xml; charset=utf-8",
            beforeSend: function(){$('#messageHTML').html(messageSaving);},
            success: function (xmlResponse) {
                var message = xmlResponse.getElementsByTagName('KetQua');
                if (message != '' || message != null)
                    alert($(message).attr('Message'));
                //Reset tất cả các field sau khi lưu phiếu khám
                ResetElement();
            }
        })
    }    
}

function ResetElement()
{
    $('#hKieuLuu').val('moi');
    $('#mapk').val('');
    $('#txtmaphieucu').val('');
    $('#txtmapk_chinh').val('');
    $('#hiden_dotkham').val('');
    $('#tenbs').html('');
    $('#hidden_LoaiKham').val('');
    $('#lblLoaiKham').html('');
    $('#mabn').val('');
    $('#hdf_DoiTuongBN').val('');
    $('#tenbn').val('');
    $('#txtSoBHYT').val('');
    $('#txtHanBHYT').val('');
    $('#ngay').val('');
    $('#tuoi').val('');
    $('#trieuchung').val('');
    $('#txtChanDoanSoBo').val('');
    $('#icd').val('');
    $('#chandoan').val('');
    $('#icdphu1').val('');
    $('#chandoanphu1').val('');
    $('#icdphu2').val('');
    $('#chandoanphu2').val('');
    $('#rgioitinh').val('0');
    $('#chidinhdieutri').val('');
    $('#loidanbs').val('');
    $('#dsxutri').val('0');
    $('#tableToaThuoc tbody').empty();
}